package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.foundations.dto.response.RegionSimpleResDTO;
import com.jzo2o.api.foundations.dto.response.ServeAggregationResDTO;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.*;
import com.jzo2o.foundations.model.domain.*;
import com.jzo2o.foundations.model.dto.request.RegionPageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.RegionUpsertReqDTO;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.*;
import com.jzo2o.foundations.service.IConfigRegionService;
import com.jzo2o.foundations.service.IRegionService;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import com.jzo2o.mysql.utils.PageUtils;
import jodd.util.StringUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 区域管理
 *
 * @author itcast
 * @create 2023/7/17 16:50
 **/
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    @Autowired
    private ServeItemMapper serveItemMapper;

    @Autowired
    private RegionMapper regionMapper;

    @Autowired
    private ServeTypeMapper serveTypeMapper;

    @Autowired
    private ServeSyncMapper serveSyncMapper;

    @Autowired
    private RestHighLevelClient client;
    /**
     * 分页查询
     * @param servePageQueryReqDTO
     * @return
     */
    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO servePageQueryReqDTO) {
        return PageHelperUtils.selectPage(servePageQueryReqDTO,
                () -> baseMapper.queryList(servePageQueryReqDTO.getRegionId()));
    }

    /**
     * 区域服务新增
     * @param dtoList
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(List<ServeUpsertReqDTO> dtoList) {
        for (ServeUpsertReqDTO dto : dtoList) {
            //服务项目必须是启用状态的才能添加到区域
            ServeItem serveItem = serveItemMapper.selectById(dto.getServeItemId());
            if (ObjectUtil.isNull(serveItem.getActiveStatus()) && serveItem.getActiveStatus() != 2){
                throw new ForbiddenOperationException("添加失败,服务项目状态有误");
            }
            //一个项目只能添加一次
            Integer count = this.lambdaQuery()
                    .eq(Serve::getRegionId, dto.getRegionId())
                    .eq(Serve::getServeItemId, dto.getServeItemId())
                    .count();
            if (count > 0){
                throw new ForbiddenOperationException("添加失败,服务项目状态有误");
            }
            //获取城市编码
            Region region = regionMapper.selectById(dto.getRegionId());
            String cityCode = region.getCityCode();
            Serve serve = BeanUtil.copyProperties(dto, Serve.class);
            serve.setCityCode(cityCode);
            //新增区域服务
            baseMapper.insert(serve);
        }
    }

    /**
     * 区域服务修改价格
     * @param id
     * @param price
     */
    @Override
    public void updateById(Long id, BigDecimal price) {
        this.lambdaUpdate()
                .eq(Serve::getId,id)
                .set(Serve::getPrice,price)
                .update();
    }

    /**
     * 区域服务删除
     * @param id
     */
    @Caching(
            evict = {
                    //删除开通区域列表
                    @CacheEvict(value = RedisConstants.CacheName.JZ_CACHE, key = "'ACTIVE_REGIONS'"),
                    //删除首页服务列表
                    @CacheEvict(value = RedisConstants.CacheName.SERVE_ICON,key = "#id")
            }
    )
    @Override
    public void deleteById(Long id) {
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve) ||serve.getSaleStatus() !=0){
            throw new ForbiddenOperationException("删除失败, 当前区域服务不是草稿状态");
        }
        //执行删除
        baseMapper.deleteById(id);
    }

    /**
     * 服务上架
     * @param id
     */
    @Override
    public void onSale(Long id) {
        //区域服务当前非上架状态
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve) || serve.getSaleStatus() == 2){
            throw new ForbiddenOperationException("当前服务已经是上架状态了");
        }
        //服务项目是启用状态
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        if (ObjectUtil.isNull(serveItem) || serveItem.getActiveStatus() != 2){
            throw new ForbiddenOperationException("服务项目未启用");
        }
        //将状态更新为上架
        this.lambdaUpdate()
                .eq(Serve::getId,id)
                .set(Serve::getSaleStatus,2)
                .update();
        //添加同步表数据
        addServeSync(id);
    }
    /**
     * 新增服务同步数据
     *
     * @param serveId 服务id
     */
    private void addServeSync(Long serveId){
        //服务信息
        Serve serve = baseMapper.selectById(serveId);
        //地域信息
        Region region = regionMapper.selectById(serve.getRegionId());
        //服务项信息
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        //服务类型信息
        ServeType serveType = serveTypeMapper.selectById(serveItem.getServeTypeId());

        //中间表信息
        ServeSync serveSync = new ServeSync();
        serveSync.setServeTypeId(serveType.getId());
        serveSync.setServeTypeName(serveType.getName());
        serveSync.setServeTypeIcon(serveType.getServeTypeIcon());
        serveSync.setServeTypeImg(serveType.getImg());
        serveSync.setServeTypeSortNum(serveType.getSortNum());

        serveSync.setServeItemId(serveItem.getId());
        serveSync.setServeItemIcon(serveItem.getServeItemIcon());
        serveSync.setServeItemName(serveItem.getName());
        serveSync.setServeItemImg(serveItem.getImg());
        serveSync.setServeItemSortNum(serveItem.getSortNum());
        serveSync.setUnit(serveItem.getUnit());
        serveSync.setDetailImg(serveItem.getDetailImg());
        serveSync.setPrice(serve.getPrice());

        serveSync.setCityCode(region.getCityCode());
        serveSync.setId(serve.getId());
        serveSync.setIsHot(serve.getIsHot());
        serveSyncMapper.insert(serveSync);

    }

    /**
     * 下架
     * @param id
     */
    @Override
    public void offSale(Long id) {
        //区域服务当前非上架状态
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve) || serve.getSaleStatus() != 2){
            throw new ForbiddenOperationException("当前服务非上架状态");
        }
        //将状态更新为下架
        this.lambdaUpdate()
                .eq(Serve::getId,id)
                .set(Serve::getSaleStatus,1)
                .update();
        //删除同步表数据
        serveSyncMapper.deleteById(id);
    }

    /**
     * 设置为热门
     * @param id
     */
    @Override
    public void onHot(Long id) {
        this.lambdaUpdate()
                .eq(Serve::getId,id)
                .set(Serve::getIsHot,1)
                .set(Serve::getHotTimeStamp,System.currentTimeMillis())
                .update();
    }

    /**
     * 取消热门
     * @param id
     */
    @Override
    public void offHot(Long id) {
        this.lambdaUpdate()
                .eq(Serve::getId,id)
                .set(Serve::getIsHot,0)
                .set(Serve::getHotTimeStamp,System.currentTimeMillis())
                .update();
    }

    /**
     * 首页服务分类
     * @param regionId
     * @return
     */
    @Caching(
            cacheable = {
                    //返回数据为空，则缓存空值30分钟，这样可以避免缓存穿透
                    @Cacheable(value = RedisConstants.CacheName.SERVE_ICON, key ="#regionId" ,
                            unless ="#result.size() > 0",cacheManager = RedisConstants.CacheManager.THIRTY_MINUTES),

                    //返回值不为空，则永久缓存数据
                    @Cacheable(value = RedisConstants.CacheName.SERVE_ICON, key ="#regionId" ,
                            unless ="#result.size() == 0",cacheManager = RedisConstants.CacheManager.FOREVER)
            }
    )
    @Override
    public List<ServeCategoryResDTO> firstPageServeList(Long regionId) {
        //1 对区域进行校验
        Region region = regionMapper.selectById(regionId);
        if (ObjectUtil.isNull(region) || region.getActiveStatus() != 2){
            return Collections.emptyList();
        }
        //2. 查询指定区域下上架的服务分类及项目信息
        List<ServeCategoryResDTO> list = baseMapper.findListByRegionId(regionId);
        if (ObjectUtil.isEmpty(list)){
            return Collections.emptyList();
        }
        //3. 截取
        list = CollUtil.sub(list, 0, Math.min(2, list().size()));
        list.forEach(e ->
                e.setServeResDTOList(CollUtil.sub(e.getServeResDTOList(),0,Math.min(4,e.getServeResDTOList().size())))
        );
        return list;
    }
    /**
     * 热门推荐
     * @param regionId
     * @return
     */
    @Caching(
            cacheable = {
                    //返回数据为空,则缓存空值30分钟,这样可以避免缓存穿透
                    @Cacheable(value = RedisConstants.CacheName.HOT_SERVE,key = "#regionId",
                    unless = "#result.size()>0",cacheManager = RedisConstants.CacheManager.THIRTY_MINUTES),
                    //返回值不为空,则永久缓存数据
                    @Cacheable(value = RedisConstants.CacheName.HOT_SERVE,key = "#regionId",
                    unless = "#result.size() == 0",cacheManager = RedisConstants.CacheManager.FOREVER)
            }
    )
    @Override
    public List<ServeAggregationSimpleResDTO> hotServeList(Long regionId) {
        //1 对区域进行校验
        Region region = regionMapper.selectById(regionId);
        if (ObjectUtil.isNull(region) || region.getActiveStatus() != 2){
            return Collections.emptyList();
        }
        //2 查询指定区域下上架且热门的服务项目信息
      return   baseMapper.findServeListByRegionId(regionId);
    }
    /**
     * 查询服务详情
     * @param id
     * @return
     */
    @Override
    public ServeAggregationSimpleResDTO findById(Long id) {
        //先根据id查询serve
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("服务不存在");
        }
        //再根据itemid查询serveItem
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        if (ObjectUtil.isNull(serveItem)){
            throw new ForbiddenOperationException("服务不存在");
        }
        ServeAggregationSimpleResDTO dto = BeanUtil.copyProperties(serve, ServeAggregationSimpleResDTO.class);
        dto.setServeItemName(serveItem.getName());
        dto.setServeItemImg(serveItem.getImg());
        dto.setDetailImg(serveItem.getDetailImg());
        dto.setUnit(serveItem.getUnit());

        return dto;
    }
    /**
     * 查询全部分类
     * @param regionId
     * @return
     */
    @Override
    public List<ServeAggregationTypeSimpleResDTO> serveTypeList(Long regionId) {
        //查询区域
        Region region = regionMapper.selectById(regionId);
        if (ObjectUtil.isNull(region)){
            return Collections.emptyList();
        }
        return baseMapper.findServeTypeListByRegionId(regionId);
    }
    /**
     * 服务搜索
     * @param cityCode
     * @param keyword
     * @param serveTypeId
     * @return
     */
    @Override
    public List<ServeSimpleResDTO> search(String cityCode, String keyword, Long serveTypeId) {
        //1.创建请求对象
        SearchRequest request = new SearchRequest("serve_aggregation");
        //2.封装请求参数
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //城市编码
        boolQuery.must(QueryBuilders.termQuery("city_code",cityCode));
        //服务类型id
        if (serveTypeId != null){
            boolQuery.must(QueryBuilders.termQuery("serve_type_id", serveTypeId));
        }
        //关键词
        if (StringUtil.isNotEmpty(keyword)){
            boolQuery.must(QueryBuilders.multiMatchQuery(keyword, "serve_item_name", "serve_type_name"));
        }
        request.source().query(boolQuery);
        request.source().sort("serve_item_sort_num", SortOrder.ASC);
        request.source().from(0).size(100);
        //3.执行请求
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //4.处理返回结果
        if(response.getHits().getTotalHits().value == 0){
            return List.of();
        }
        return Arrays.stream(response.getHits().getHits())
                .map( e -> JSONUtil.toBean(e.getSourceAsString(), ServeSimpleResDTO.class))
                .collect(Collectors.toList());
    }
    /**
     * 查询服务详情
     * @param id
     * @return
     */
    @Override
    public ServeAggregationResDTO findServeDetailById(Long id) {
        return baseMapper.findServeDetailById(id);
    }
}
